package cfca.seal.mananger;

import cfca.seal.bean.SealCert;
import cfca.seal.common.LRUCache;
import cfca.seal.dao.main.ISealCertDao;
import cfca.seal.exception.CodeException;
import javax.annotation.Resource;
import javax.servlet.ServletContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

public class SealCertManager
{
  private static final Logger log = LoggerFactory.getLogger("web_sys");
  static final int cacheSize = 200;
  private static LRUCache<String, SealCert> sealCertMap = new LRUCache(200);
  private static SealCertManager instance = null;

  @Resource
  ISealCertDao dao;

  public static SealCertManager getInstance() { if (instance == null) {
      instance = new SealCertManager();
    }
    return instance;
  }

  public void init(ServletContext servletContext)
  {
    synchronized (this) {
      WebApplicationContext wac = WebApplicationContextUtils.getWebApplicationContext(servletContext);
      this.dao = ((ISealCertDao)wac.getBean(ISealCertDao.class));
    }
  }

  public SealCert getSealById(String id) throws Exception {
    SealCert sealCert = (SealCert)sealCertMap.get(id);
    if (sealCert == null) {
      sealCert = this.dao.getSealCertById(id);
      if (sealCert != null)
        sealCertMap.put(id, sealCert);
    }
    return sealCert;
  }

  public void addSealCert(SealCert sealCert) throws CodeException {
    synchronized (this) {
      sealCertMap.put(sealCert.getId(), sealCert);
      log.info("印章证书管理容器增加新的证书:" + sealCert.getId());
    }
  }

  public void removeSealCert(String id) {
    synchronized (this) {
      sealCertMap.remove(id);
      log.info("印章证书管理容器删除证书:" + id);
    }
  }
}